import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, message } from 'antd';
import moment from 'moment';
import { DATA_ENTRY, AdvancedSearch, SecondHeaderC, NoQueryC, ExportFrontEndC, PrimaryGhostC, ContentPackage } from '../../../components';
import Info from './info'; // 时点信息
import PortfolioInfo from './PortfolioInfo'; // 组合信息
import Constitute from './constitute'; // 产品组构成
import ShowRanking from './showRanking'; // 排名
import ShowEchartsOne from './showEchartsOne'; // 产品收益率
import ShowEchartsTwo from './showEchartsTwo'; // 区间统计
import ShowEchartsThree from './showEchartsThree'; // 大类资产收益率
import ShowEchartsFour from './showEchartsFour'; // 明细资产收益率
import ShowTable from './showTable'; // 明细
import { isZiGuanEvir } from '../../../utils/commonFunc';
import isHaveNetValue from '../utils/isHaveNetValue';
import { useExportMoreTableInSheet } from '@/src/utils/exportExcelHooks';

@connect(({ yieldPerformanceM, productAGroupM }) => ({
  yieldPerformanceM,
  productAGroupM,
}))
export default class YieldPerformance extends PureComponent {
  state = {
    searchData: {
      portfolioCodeList: [],
      portfolioCode: '',
      portfolioName: '',
    },
    propsData: {
      portfolioCodeList: [],
      portfolioCode: '',
      timeRange: '0',
      beginDate: '',
      endDate: '',
      portfolioName: '',
    },
    type: '', // 1产品 2组合 3产品组
    isShow: false,
    codeKey: null, // 用于匹配产品的唯一标识
  };

  componentDidMount = () => {
    this.getStorageData();
  };

  // 产品组改变
  handPortfolioCodeListChange = (e) => {
    if (e) {
      this.state.PRODUCTGROUPTREE.setSelect();
      // this.searchForm.formRef.current.resetFields(['portfolioCode']); // 重置组合和产品
      // this.state.RANGEDATE.reset();
      this.setState({ type: 3 });
      if (e?.info?.children.length > 0) {
        this.setState({
          searchData: {
            portfolioCodeList: e?.key,
            portfolioCode: '',
            portfolioName: e?.info?.title,
          },
        });
      } else {
        message.warning('该组合下无产品');
        this.setState({
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
            portfolioName: '',
          },
        });
      }
    } else {
      this.state.RANGEDATE.reset();
      this.setState({
        searchData: {
          portfolioCodeList: '',
          portfolioCode: '',
        },
      });
    }
  };

  // 产品
  prodectChange = (e) => {
    if (e) {
      if (isZiGuanEvir()) {
        this.setState({ type: 1 });
      } else if (this.props.productAGroupM.productGroup?.some((x) => x.key == e.key)) {
        this.setState({ type: 1 });
      } else {
        this.setState({ type: 2 });
      }

      this.searchForm.formRef.current.resetFields(['portfolioCodeList']);
      this.setState({
        searchData: {
          portfolioCodeList: '',
          portfolioCode: e.info?.portfolioCode,
          portfolioName: e.info?.portfolioName,
        },
      });
    } else {
      this.setState(
        {
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
            portfolioName: '',
          },
        },
        () => {
          this.state.RANGEDATE.reset();
        },
      );
    }
  };

  // 搜索点击事件
  setPorpsData = async (e) => {
    const { searchData } = this.state;
    if (searchData?.portfolioCode || searchData?.portfolioCodeList) {
      if (e.beginDate && e.endDate) {
        const portfolio = {};
        if (searchData.portfolioCode) {
          portfolio.portfolioCode = searchData.portfolioCode;
        } else if (searchData.portfolioCodeList) {
          portfolio.portfolioCodeList = searchData.portfolioCodeList;
        }
        if (
          !(await isHaveNetValue({
            ...portfolio,
            endDate: e.endDate.format('YYYY-MM-DD'),
          }))
        )
          return;
        if (e.timeRange == '3' || e.timeRange == '4' || e.timeRange == '5' || e.timeRange == '6') message.warning('数据加载时间可能较长请耐心等待!');
        this.setState({
          propsData: {
            timeRange: e.timeRange || '0',
            portfolioCode: searchData.portfolioCode,
            portfolioCodeList: searchData.portfolioCodeList,
            beginDate: e.beginDate.format('YYYY-MM-DD'),
            endDate: e.endDate.format('YYYY-MM-DD'),
            portfolioName: searchData.portfolioName,
            type: this.state.type,
          },
          isShow: true,
        });
      } else {
        message.warning('请选择时间区间');
      }
    } else {
      message.warning('选择产品组或产品');
    }
  };

  // 收益率柱状图和区间收益率切换数据类型
  changeEchartType = (e) => {
    this.EchartsOneRef && this.EchartsOneRef.refresh(e);
    this.EchartsTwoRef && this.EchartsTwoRef.refresh(e);
  };

  // 优化columns的渲染
  newColumns = (columns) => {
    const newColumns = columns;
    if (newColumns && newColumns.length) {
      newColumns.map((item) => {
        if (item.key == 'product' || item.key == 'bench' || item.key == 'balance') {
          item.title += '（%）';
        }
      });
    }
    return newColumns;
  };

  // echart数据转table
  echartsToTable(data, columns) {
    if (!data.xAxis) return;
    const dataSource = [];
    data?.xAxis.map((item) => {
      const obj = {
        [columns[0].key]: item,
      };
      dataSource.push(obj);
    });
    dataSource.map((item, index) => {
      data?.series.map((seriesItem) => {
        columns.map((columnsItem) => {
          if (seriesItem.name == columnsItem.title) {
            item[columnsItem.key] = seriesItem.data[index];
          }
        });
      });
    });
    return dataSource;
  }

  changeTableData(data) {
    const columns = [
      { title: '资产类别', key: 'assetType' },
      { title: '代码', key: 'tradingCode' },
      { title: '简称', key: 'securityName' },
      { title: '持仓类型', key: 'posType' },
      { title: '交易属性', key: 'tradeAttr' },
      { title: '平均权重%', key: 'productAvgWeight' },
      { title: '收益率%', key: 'productYield' },
      { title: '收益率贡献%', key: 'productYieldAttribute' },
      { title: '平均权重%', key: 'benchAvgWeight' },
      { title: '收益率%', key: 'benchYield' },
      { title: '收益率贡献%', key: 'benchYieldAttribute' },
      { title: '平均权重%', key: 'balanceAvgWeight' },
      { title: '收益率%', key: 'balanceYield' },
      { title: '收益率贡献%', key: 'balanceYieldAttribute' },
    ];
    let dataSource = [];
    if (data && data.length) {
      data.map((item, index) => {
        const obj = {};
        const arr = [];
        let arrItem = [];
        if (item.children && item.children.length) {
          arrItem = this.changeTableData(item.children);
        }
        columns.map((columnsItem) => {
          obj[columnsItem.key] = item[columnsItem.key];
        });
        arr.push(obj);
        dataSource = [...dataSource, ...arr, ...arrItem];
      });
    }
    return dataSource;
  }

  // 一个工作表导出内多个table
  moreTableInSheetExport = () => {
    const { portfolioName, portfolioCodeList, portfolioCode } = this.state.propsData;
    const {
      yieldPerformanceM: { echartsOne, echartsTwo, TableData, infoData },
    } = this.props;
    const columns = [
      {
        key: 'date',
        title: '日期',
      },
      {
        key: 'product',
        title: '组合',
      },
      {
        key: 'bench',
        title: '基准',
      },
      {
        key: 'balance',
        title: '超额',
      },
    ];
    const dataSource3 = this.changeTableData(TableData.dataSource);
    const groupedHeader = [
      // type是2时的xlsxData表头
      ['资产类别', '代码', '简称', '持仓类型', '交易属性', '产品', '', '', '基准', '', '', '超额', '', ''],
      ['', '', '', '', '', '平均权重(%)', '收益率(%)', '收益率贡献(%)', '平均权重(%)', '收益率(%)', '收益率贡献(%)', '平均权重(%)', '收益率(%)', '收益率贡献(%)'],
    ];

    // 控制表格中不显示'当日'的数据
    echartsOne.xAxis.splice(0, 1);
    const removeData = echartsOne.series.reduce((acc, item) => {
      // 移除数组中的第一个元素
      const removed = item.data.splice(0, 1)[0];
      // 将移除的元素追加到新数组中
      return acc.concat(removed);
    }, []);

    const tableData = this.echartsToTable(echartsOne, columns);
    const tableDatatwo = this.echartsToTable(echartsTwo, columns);
    if (tableData && tableData.length && infoData && infoData.dailyRate) {
      const obj = {
        date: '日收益率',
        product: removeData[0],
        bench: removeData[1],
        balance: removeData[2],
        // product: infoData.dailyRate.yield,
        // bench: 0,
        // balance: infoData.dailyRate.yield - 0,
      };
      tableData.unshift(obj);
    }
    const newColumns = this.newColumns(columns);
    const sheetConfig = {
      表名: {
        sheetBody: [
          {
            type: 3,
            anyXlsxData: [
              [`产品代码：${portfolioCode || portfolioCodeList}`, `产品名称：${portfolioName}`, `起始日期:${this.state.propsData.beginDate}~${this.state.propsData.endDate}`, ''],
            ],
          },
          {
            type: 3,
            anyXlsxData: [[''], ['区间收益率', '', '', '']],
          },
          {
            type: 1, // 类型1时普通表头传普通columns
            columns: newColumns,
            dataSource: tableData,
          },
          {
            type: 3,
            anyXlsxData: [[''], ['区间趋势', '', '', '']],
          },
          {
            type: 1,
            columns: newColumns,
            dataSource: tableDatatwo,
          },
          {
            type: 3,
            anyXlsxData: [[''], ['收益率明细', '', '', '']],
          },
          {
            type: 2, // 为2是为分组表头， 不传column传groupedHeader
            groupedHeader,
            dataSource: dataSource3,
          },
        ],
        columnWidth: [{ wpx: 100 }, { wpx: 120 }, { wpx: 100 }], // 列1： 100，列2： 120， 列3： 100
        mergeRules: [
          { s: { r: 0, c: 2 }, e: { r: 0, c: 3 } }, // 合并第1行 1到2列
          { s: { r: 2, c: 0 }, e: { r: 2, c: 3 } }, // 合并第3行 1到4列
          { s: { r: tableData.length + 5, c: 0 }, e: { r: tableData.length + 5, c: 3 } },
          { s: { r: tableData.length + tableDatatwo.length + 8, c: 0 }, e: { r: tableData.length + tableDatatwo.length + 8, c: 3 } }, // 合并第17行 1到4列
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 5 }, e: { r: tableData.length + tableDatatwo.length + 9, c: 7 } },
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 8 }, e: { r: tableData.length + tableDatatwo.length + 9, c: 10 } },
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 11 }, e: { r: tableData.length + tableDatatwo.length + 9, c: 13 } },
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 0 }, e: { r: tableData.length + tableDatatwo.length + 10, c: 0 } }, // 合并第18行到19行 第1列
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 1 }, e: { r: tableData.length + tableDatatwo.length + 10, c: 1 } }, // 合并第18行到19行 第2列
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 2 }, e: { r: tableData.length + tableDatatwo.length + 10, c: 2 } }, // 合并第18行到19行 第3列
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 3 }, e: { r: tableData.length + tableDatatwo.length + 10, c: 3 } }, // 合并第18行到19行 第4列
          { s: { r: tableData.length + tableDatatwo.length + 9, c: 4 }, e: { r: tableData.length + tableDatatwo.length + 10, c: 4 } }, // 合并第18行到19行 第5列
        ],
        callback: (ws) => {
          // A1,B1,C1 对应xlsx文件打开时的A1,B1,C1
          const oneTitle = ['A1', 'B1', 'C1'];
          // 一级标题设置背景
          oneTitle.map((v) => {
            ws[v].s = {
              fill: { fgColor: { rgb: 'e8efff' } }, // A3背景
            };
          });
          ws.A3.s = {
            fill: { fgColor: { rgb: 'e8efff' } }, // A3背景
          };
          ws.A12.s = {
            fill: { fgColor: { rgb: 'e8efff' } }, // A10背景
          };
          ws[`A${tableData.length + tableDatatwo.length + 9}`].s = {
            fill: { fgColor: { rgb: 'e8efff' } }, // A17背景
          };
          return ws;
        },
      },
    };
    useExportMoreTableInSheet(sheetConfig, `${portfolioCode || portfolioCodeList}-${portfolioName} ${this.state.propsData.beginDate}~${this.state.propsData.endDate}`);
  };

  // 从组合概览跳转   拿到sessionStorage中的查询条件
  getStorageData = () => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    if (overviewData) {
      const { portfolioCode, portfolioName, timeRange, beginDate, endDate } = overviewData;

      this.setState({
        searchData: {
          portfolioCode,
          timeRange,
          beginDate,
          endDate,
        },
      });
    }
  };

  // 获取子组件接口返回的数据用于匹配code
  changePortfolioCodeInitValue = (data) => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    sessionStorage.removeItem('searchObj');
    const { portfolioCode } = overviewData || {};
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.portfolioCode === portfolioCode) {
        this.setState(
          {
            codeKey: item.key,
          },
          () => {
            // 更新数据完成之后触发查询
            const { codeKey } = this.state;
            const { beginDate, endDate, timeRange } = this.state.searchData;
            const changeSearchData = { beginDate: moment(beginDate), endDate: moment(endDate), timeRange, portfolioCode: codeKey };
            this.setPorpsData(changeSearchData);
          },
        );
      }
    }
  };

  render() {
    const { searchData, codeKey } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioCodeList',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          multiple: false,
          disabled: isZiGuanEvir(),
          onRef: (ref) => this.setState({ PRODUCTGROUP: ref }),
          onChange: this.handPortfolioCodeListChange,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'],
        },
        {
          dataIndex: 'portfolioCode',
          title: '产品',
          type: isZiGuanEvir() ? DATA_ENTRY.PRODUCTLIST : DATA_ENTRY.PRODUCTGROUPTREE,
          multiple: false,
          onRef: (ref) => this.setState({ PRODUCTGROUPTREE: ref }),
          onChange: this.prodectChange,
          ...(isZiGuanEvir() ? { dataType: 2 } : null),
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'],
          changePortfolioCodeInitValue: this.changePortfolioCodeInitValue,
          initialValue: codeKey,
        },
        searchData.portfolioCode
          ? {
              selectIndex: 'timeRange',
              startIndex: 'beginDate',
              endIndex: 'endDate',
              type: DATA_ENTRY.HOlDDATERANGEC,
              productCode: searchData.portfolioCode,
              flag: '2',
              defaultType: searchData.timeRange || '2',
              initialValue: searchData.beginDate && { beginDate: moment(searchData.beginDate), endDate: moment(searchData.endDate) },
            }
          : {
              type: DATA_ENTRY.RANGEDATE,
              dataIndex: ['beginDate', 'endDate'],
              title: '时间区间',
              disabled: !searchData.portfolioCode && !searchData.portfolioCodeList,
              onRef: (ref) => this.setState({ RANGEDATE: ref }),
            },
      ],
      onQuery: (e) => {
        this.setPorpsData(e);
      },
      onClear: () => {
        this.setState({
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
            portfolioName: '',
          },
          codeKey: '', // 清空产品框
        });
      },
    };

    const { portfolioName, type, portfolioCodeList, portfolioCode, ...others } = this.state.propsData;
    const args = portfolioCode
      ? {
          portfolioCode,
          ...others,
        }
      : {
          portfolioCodeList,
          ...others,
        };

    return (
      <ContentPackage
        title='收益率表现'
        contentHtml={
          <div style={isZiGuanEvir() ? { padding: '0 12px', overflowY: 'auto', height: 'inherit' } : {}}>
            <div>
              <AdvancedSearch {...searchProps} onRef={(ref) => (this.searchForm = ref)} />
            </div>
            {this.state.isShow ? (
              <div>
                <div>
                  <div style={{ marginTop: '10px' }}>
                    <SecondHeaderC title={portfolioName} Right={<PrimaryGhostC title='导出' onClick={this.moreTableInSheetExport} />} />
                  </div>
                  {/* 产品 */}
                  {type === 1 && <Info portfolioName={portfolioName} args={args} />}
                  {/* 组合信息 */}
                  {type === 2 && <PortfolioInfo portfolioName={portfolioName} args={args} />}
                </div>

                {/* 组合时这个模块不展示 */}
                {type != 2 && (
                  <div style={{ marginTop: '10px' }}>
                    <Row gutter={16}>
                      <Col span={12}>
                        <ShowEchartsOne args={args} onRef={(ref) => (this.EchartsOneRef = ref)} changeEchartType={this.changeEchartType} />
                      </Col>
                      <Col span={12}>
                        {/* 产品收益率排名 */}
                        {type == 1 && <ShowRanking args={args} />}
                        {/* 产品组构成 */}
                        {type == 3 && <Constitute args={args} />}
                      </Col>
                    </Row>
                  </div>
                )}
                <div style={{ marginTop: '20px' }}>
                  <SecondHeaderC title='区间统计' />
                  <ShowEchartsTwo args={args} type={type} onRef={(ref) => (this.EchartsTwoRef = ref)} changeEchartType={this.changeEchartType} />
                </div>
                <div style={{ marginTop: '20px' }}>
                  <Row gutter={16}>
                    <Col span={12}>
                      <ShowEchartsThree args={args} />
                    </Col>
                    <Col span={12}>
                      <ShowEchartsFour args={args} />
                    </Col>
                  </Row>
                </div>
                <div style={{ marginTop: '20px' }}>
                  <SecondHeaderC title='收益率明细' />
                  <ShowTable args={args} />
                </div>
              </div>
            ) : (
              <div style={{ marginTop: '20px' }}>
                <NoQueryC />
              </div>
            )}
          </div>
        }
      />
    );
  }
}
